source('dados.R')
source('cenas/rndgen.R')

# Exemplos de uso:
#
# PlotDanos(100, 1)
# PlotDanos(100, 2)
# PlotDanos(100, 100)
#
# com limite:
# PlotDanos(100, 100, 1000)
#
# gastos:
# PlotGastos(100, 100, 20, 300)
#
# optimizacao:  (calculos)
# OptimiseRuin(100, 20, .2)


merge_vecs <- function(v1, v2)
{
	v <- rep(0, length(v1)*2)
	for(i in 1:length(v1)) {
		v[(i-1)*2+1] <- v1[i]
		v[(i-1)*2+2] <- v2[i]
	}
	v
}

###################### Estatística ######################

my_rexp <- function(nanos, lambda)
{
	T <- cumsum(rexp(lambda*nanos, rate=1/lambda))
	lT <- T[length(T)]
	while((lT <- T[length(T)]) < nanos)
		T <- c(T, cumsum(rexp(100, rate=1/lambda)) + lT)
	T[T < nanos]
}

rfn <- function(m) rndgen(m, fdp, lfdp, 2, lmean, lsd)

###################### Plot ######################

PlotDanos <- function(nanos, N, Xlim=0)
{
	Tlim <- NULL
	ylim <- c(0, mean(Danos) * length(Danos) * 2)
	Xlosses <- rep(0, N)

	for(i in 1:N) {
		lambda <- NAnos/length(Danos)
		T <- my_rexp(nanos, lambda)
		ndanos <- length(T)
		T <- c(0, merge_vecs(T, T), nanos)

		X <- cumsum(c(0, rfn(ndanos)))
		X <- merge_vecs(X, X)

		p <- if(i == 1) plot else lines
		p(type='l',
			T, X,
			col=rgb(0,0,1,.2), lwd=2,
			main='Simulação Danos',
			xlab='Anos', ylab='Danos',
			xlim=c(0,nanos), ylim=ylim)

		if(Xlim != 0) {
			if(i == 1)
				lines(c(0,nanos), c(Xlim,Xlim), col=rgb(1,0,0,1), lwd=2)

			v <- X > Xlim
			if(any(v)) {
				t <- T[which(v)[1]]
				lines(c(t,t), c(0,Xlim), col=rgb(1,0,0,.2), lwd=2)
				Tlim[length(Tlim)+1] <- t
			}
		}
		Xlosses[i] <- X[length(X)]
	}

	if(Xlim != 0 && N > 1)
		text(
			0, ylim[2],
			paste('média:', round(mean(Tlim),2), '\ndesvio:', round(sd(Tlim),2)),
			c(0,1))
	Xlosses
}

PlotGastos <- function(nanos, N, canos, c.)
{
	Tlim <- NULL
	ylim <- c(-1000, +1500)
	F <- rep(0, N)
	Xlosses <- NULL


	ruins <- 0
	for(i in 1:N) {
		lambda <- NAnos/length(Danos)
		T <- my_rexp(nanos, lambda)
		T <- c(T, seq(1,nanos,by=canos))
		T <- sort(T)

		X <- NULL
		x <- 0
		T. <- NULL
		for(t in T) {
			ox <- x
			if(((t-1) %% canos) == 0)
				x <- x + c.
			else
				x <- x - rfn(1)
			if(t == 1)
				ox <- x
			X[length(X)+1] <- ox
			X[length(X)+1] <- x
			T.[length(T.)+1] <- t
			T.[length(T.)+1] <- t
		}
		T <- c(T., nanos)
		X <- c(X, X[length(X)])

		col = if(X[length(X)] < 0) { ruins <- ruins+1 ; rgb(1,0,1,.2) } else rgb(0,1,1,.2)
		F[i] <- X[length(X)]

		p <- if(i == 1) plot else lines
		p(type='l',
			T, X,
			col=col, lwd=2,
			main='Simulação Gastos',
			xlab='Anos', ylab='Gastos',
			xlim=c(0,nanos), ylim=ylim)

		Xl <- X[length(X)]
		if(Xl < 0)
			Xlosses[length(Xlosses)+1] <- Xl
	}

	title <- paste('Profit at T=', nanos)
	legend('topright',
		#title=title,
		c('> 0', '< 0'), lwd=c(2,2),
		col=c(rgb(0,1,1,.2), rgb(1,0,1,.2)),
		bg='white', cex=.8)

	ruins <- ruins/N
	lines(c(0,nanos), c(0,0), col=rgb(1,0,0,1), lwd=2)
	if(N > 1) {
		text(nanos, +50, paste((1-ruins)*100, '%'), c(1, 0))
		text(nanos, -50, paste(ruins*100, '%'), c(1, 1))
		text(
			0, ylim[2],
			paste(title, '\n\nmédia:', round(mean(F),2), '\ndesvio:', round(sd(F),2)),
			c(0,1))
	}
#	ruins
	Xlosses
}

CalcRuinas <- function(nanos, N, canos, c., draw=TRUE)
{
	ruins <- 0
	for(i in 1:N) {
		lambda <- NAnos/length(Danos)
		T <- my_rexp(nanos, lambda)
		X <- sum(rfn(length(T)))
		R <- c. * (nanos / canos)
		if(R - X < 0)
			ruins <- ruins +1
	}
print(paste(c., ruins/N))
	ruins/N
}

OptimiseRuin <- function(nanos, canos, ruin)
{
	# we want to equal ruin, so we subtract the solution and apply an abs (then minimize that)

	gastos <- function(c.) abs(CalcRuinas(nanos, 1000, canos, c., FALSE) - ruin)
	optimise(gastos, lower=0, upper=1000, maximum=FALSE, tol=50)
}

